package com.jgp.security.shiro.component;

import com.jgp.security.config.SecUserAdapter;
import com.jgp.security.pojo.UserInfo;
import com.jgp.security.secmodel.SecUser;
import com.jgp.security.service.SecUserService;
import com.jgp.sys.utils.SpringContextUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Component;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2019/1/10
 */
@Component
public class ShiroUserAdapter implements SecUserAdapter {
    
    @Override
    public boolean checkPwd(String userId, String pwd) {
        SecUserService userService = SpringContextUtil.getBean(SecUserService.class);
        SecUser user = userService.query(userId);
        return user.getPassword().equals(encryptPwd(pwd,user.getSugar(),user.getEncryptTime()));
    }
    
    @Override
    public void resetPwd(String userId, String pwd) {
        SecUserService userService = SpringContextUtil.getBean(SecUserService.class);
        userService.resetPassword(userId,pwd);
    }
    
    @Override
    public String encryptPwd(String plainPwd,String sugar,Integer encryptTime) {
        Md5Hash hash = new Md5Hash(plainPwd, sugar, encryptTime);
        return hash.toHex();
    }
    
    @Override
    public UserInfo currentUser() {
        UserInfo user = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        return user;
    }
    
    public static void main(String[] args) {
        System.out.println(new ShiroUserAdapter().encryptPwd("yantai0535","@adc==",2));
    }
}
